<template>
  <el-form ref="form"
    :model="user"
    :rules="rules"
    label-width="130px">
    <el-form-item :label="$t('personalCenter.oldPassword')"
      prop="oldPassword">
      <el-input v-model="user.oldPassword"
        :placeholder="$t('personalCenter.oldPwdTips')"
        type="password"
        show-password />
    </el-form-item>
    <el-form-item :label="$t('personalCenter.newPassword')"
      prop="newPassword">
      <el-input v-model="user.newPassword"
        :placeholder="$t('personalCenter.newPwdTips')"
        type="password"
        show-password />
    </el-form-item>
    <el-form-item :label="$t('personalCenter.confirmPassword')"
      prop="confirmPassword">
      <el-input v-model="user.confirmPassword"
        :placeholder="$t('personalCenter.newPwdConfirm')"
        type="password"
        show-password />
    </el-form-item>
    <el-form-item>
      <el-button type="primary"
        size="mini"
        @click="submit">{{$t('common.save')}}</el-button>
      <el-button type="danger"
        size="mini"
        @click="close">{{$t('common.close')}}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUserPwd } from "@/api/system/user";

export default {
  data () {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error(this.$t('personalCenter.twoPwdDif')));
      } else {
        callback();
      }
    };
    return {
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      // 表单校验
      rules: {
        oldPassword: [
          { required: true, message: this.$t('common.ruleInputEmpty'), trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: this.$t('common.ruleInputEmpty'), trigger: "blur" },
          { min: 6, max: 20, message: this.$t('personalCenter.pwdLength'), trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: this.$t('common.ruleInputEmpty'), trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    submit () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateUserPwd(this.user.oldPassword, this.user.newPassword).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccessfully'));
          });
        }
      });
    },
    close () {
      this.$tab.closePage();
    }
  }
};
</script>
